from rest_framework import viewsets, generics, mixins
from users.models import UserAddress, User, UserAvatar, Logo
from users.serializers import (
    UserRegisterSerializer,
    GetUserAddressSerializer,
    UserBaseInfosUpdateSerializers,
    UserAvatarSerializer,
    PostUserAdressSerializer,
    LogoSerializer,
)
from rest_framework import permissions
from rest_framework_jwt.serializers import jwt_payload_handler
from rest_framework_jwt.serializers import jwt_encode_handler
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.views import APIView
from rest_framework.response import Response
import os
import requests
from datetime import time
from django.conf import settings
from rest_framework.decorators import api_view
import json
from PIL import Image, ImageDraw, ImageFont

# 用户详情/注册视图继承了mixins扩展类--想使用扩展类必须也继承viewsets.GenericViewSet
class UserViewset(
    mixins.CreateModelMixin,
    viewsets.GenericViewSet,
    mixins.RetrieveModelMixin,
    mixins.ListModelMixin,
    mixins.UpdateModelMixin,
):
    """
    User-Register--Only Post
    """

    queryset = User.objects.all()
    authentication_classes = [JSONWebTokenAuthentication]

    def list(self, request):
        """
        只有已验证到用户登录才能获取自己到用户信息
        """
        user = self.request.user
        ser = UserRegisterSerializer(user)
        return Response(ser.data)

    def get_object(self):
        return self.request.user

    def get_permissions(self):
        """
        由于此接口包含注册功能，所以身份验证需要区别对待
        """
        if self.action == "list" or self.action == "update":
            permission_classes = [permissions.IsAuthenticated]
        else:
            permission_classes = [permissions.AllowAny]
        return [permission() for permission in permission_classes]

    def get_serializer_class(self):
        if self.action == "update":
            serializer_class = UserBaseInfosUpdateSerializers
        else:
            serializer_class = UserRegisterSerializer
        return serializer_class


# 用户地址创建/列表视图
class UserAddressViewset(
    viewsets.GenericViewSet,
    mixins.CreateModelMixin,
    mixins.ListModelMixin,
    mixins.RetrieveModelMixin,
    mixins.UpdateModelMixin,
    mixins.DestroyModelMixin,
):
    """
    UserAddress-List-Create
    """

    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = [JSONWebTokenAuthentication]

    # 根据请求到用户自动生成owner字段值
    def perform_create(self, serializers):
        serializers.save(owner=self.request.user)

    def get_queryset(self):  #  单个用户可以有多个地址，所以使用get_queryset()而不是get_object()
        user = self.request.user
        queryset = UserAddress.objects.filter(owner=user)
        return queryset

    def get_serializer_class(self):

        if self.action == "create":
            serializer_class = PostUserAdressSerializer
        else:
            serializer_class = GetUserAddressSerializer
        return serializer_class


class UserAvatarViewset(
    viewsets.GenericViewSet,
    mixins.ListModelMixin,
    mixins.UpdateModelMixin,
    mixins.CreateModelMixin,
    mixins.RetrieveModelMixin,
):
    """
    User-Avatar
    """

    serializer_class = UserAvatarSerializer
    permission_classes = [permissions.IsAuthenticated]
    authentication_classes = [JSONWebTokenAuthentication]

    def get_queryset(self):
        getall = self.request.query_params.get("all", None)
        owner = self.request.user
        if getall is not None:
            queryset = UserAvatar.objects.filter(owner=owner)
        else:
            queryset = UserAvatar.objects.all().order_by("id")
        return queryset

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

    def post(self, request):
        serializer = UserAvatarSerializer(data=request.data)
        if serializer.is_valid():
            name = str(time.time()).split(".")[0].strip()
            # suffix = request.data["suffix"].split(r'"')[1].strip()
            avatar_name = "avatar/{}/{}".format(request.user.username, name)
            avatar = Image.open(request.data["avatar"])  # 获得图片
            if not os.path.exists("media/avatar/" + request.user.username):
                os.makedirs("media/avatar/" + request.user.username)
            avatar_file_path = os.path.join(settings.MEDIA_ROOT, avatar_name).replace(
                "\\", "/"
            )
            avatar.save(avatar_file_path)
            # UserAvatar.objects.filter(owner=request.user).update(
            #     avatar=avatar_file_path
            # )


## logo
class LogoViewset(
    viewsets.GenericViewSet,
    mixins.CreateModelMixin,
    mixins.ListModelMixin,
    mixins.RetrieveModelMixin,
):
    serializer_class = LogoSerializer
    queryset = Logo.objects.all()

    def post(self, request):
        ser = LogoSerializer(data=request.data)
        if ser.is_valid():
            name = str(time.time()).split(".")[0].strip()
            logo_name = "avatar/{}/{}".format(request.user.username, name)
            logo = Image.open(request.data["avatar"])  # 获得图片
            if not os.path.exists("media/logo/" + request.user.username):
                os.makedirs("media/logo/" + request.user.username)
            logo_file_path = os.path.join(settings.MEDIA_ROOT, logo_name).replace(
                "\\", "/"
            )
            logo.save(logo_file_path)


## 定义获取openid的函数
def getOpenid(code):
    url = "https://api.weixin.qq.com/sns/jscode2session"
    appid = "wxa9ee85d366ef2cb9"
    scrct = "8a9929c4ed1d43c318da6f2626b8bb4a"
    url2 = (
        url
        + "?appid="
        + appid
        + "&secret="
        + scrct
        + "&js_code="
        + code
        + "&grant_type=authorization_code"
    )
    res = requests.get(url2)
    print(res)
    try:
        openid = res.json()["openid"]
        session_key = res.json()["session_key"]
    except KeyError:
        return "fail"
    else:
        return {"openid": openid, "session_key": session_key}


## 微信登录接口
@api_view(["POST"])
def wxlogin(request):
    code = request.data["code"]
    res = getOpenid(code)
    try:  #  判断是否存在用户信息
        user = User.objects.get(username=res["openid"])
    except:  # 不存在则创建对应的用户信息
        user = None
    if user:
        user = User.objects.get(username=res["openid"])
    else:
        newuser = {
            "username": res["openid"],
            "password": res["openid"],
            "mobile": 13636522145,
        }
        ser = UserRegisterSerializer(data=newuser)
        if ser.is_valid():
            ser.save()
        else:
            print("用户数据不合法")

    user = User.objects.get(username=res["openid"])

    ## 根据上面的user来生成token
    payload = jwt_payload_handler(user)
    token = jwt_encode_handler(payload)
    res = {"status": "200", "nickname": "cassoShop", "user_id": user.id, "token": token}
    return Response(res)
